<template>
  <div class="container">
    <template v-if="loaded">
      <navbar ref="navbar" :title="title" showTitle="title" theme="gradient" :titleNode="!title"
              :leftItemIcon="'\ue600'"
              :leftItemText="searchFromTitle || leftTitle"
              :leftShow="navbarLeftShow" :rightShow="navbarRightShow"
              :rightItemText="selMode ? '取消' : '选品'"
              @rightItemClick="navbarRightClick">
        <searchbar theme="light" class="flex-1"
                   :disabled="searchFrom ? false : true"
                   slot="titleNode" :keywords="itemSearchParam.keywords"
                   @search="searchBarSearch"
                   @click="searchbarClick()"></searchbar>
      </navbar>
      <list class="item-list-container" @scroll="onPageScroll">
        <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                      :indicatorScale="indicatorScale"></page-refresh>
        <header>
          <div class="adv-list" ref="top" v-if="advSpaceId">
            <adv-slider :adv-space-id="advSpaceId" border-radius="0"></adv-slider>
          </div>
          <div class="adv-list" ref="top" v-else>
            <adv-slider adv-space-code="COMMISSION_ITEM_SEARCH_PAGE" border-radius="0"></adv-slider>
          </div>
        </header>
        <header>
          <div class="shopcat-scrollbar" ref="shopcatBar" v-if="showShopcatBar && (searchFrom==='' || searchFrom === 'SITE')">
            <shopcat-scrollbar v-on:shopcatSelected="shopcatSelected"
                               :shopcatIds="itemSearchParam.catIds"></shopcat-scrollbar>
          </div>
          <div class="shopcat-scrollbar" ref="materialBar" v-if="taobaoMaterialCatId && (searchFrom==='TAOBAO')">
            <material-scrollbar v-on:materialSelected="materialSelected"
                               :catId="taobaoMaterialCatId"></material-scrollbar>
          </div>
          <filterbar v-if="!taobaoMaterialCatId" :param="itemSearchParam" :hideEcomPlat="hideEcomPlat" :searchFrom="searchFrom"
                     v-on:change="filterbarChange" layout="list" @layout="listLayout"></filterbar>
          <div class="coupon-filter" v-if="searchFrom !== '' && !taobaoMaterialCatId">
            <text class="coupon-filter-title">仅搜索优惠券商品</text>
            <xswitch @change="couponSwitchChange"></xswitch>
          </div>
        </header>
        <template v-if="commissionItemList.length"
                  v-for="(itemList, rowIdx) in commissionItemRowList">
          <item-cell v-bind:key="rowIdx" :layout="commissionItemListLayout" @commissionItemClick="commissionItemClick" @commissionItemSel="commissionItemSel"
                     :showSelBtn="selMode" :itemList="itemList"></item-cell>
        </template>
        <cell>
          <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon" v-if="!commissionItemList.length && !hasNext"></page-notice>
        </cell>
        <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                           :shown="hasNext"></page-loading-more>
      </list>
      <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop"></page-scrolltop>
      <wxc-loading :show="loadingShow"></wxc-loading>
      <user-item-selection :show="selMode" :itemList="itemSelectionCart.userItemSelectList"></user-item-selection>
    </template>
    <page-loading :loaded="loaded"></page-loading>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/utilities";
  @import "./sass/icon";
  @import "./sass/buttons";

  .container {
    background-color: $body-bg;
    transition: transform .3s linear;
    width: 750px;
    position: relative;
  }

  .shopcat-scrollbar {
    background-color: #ffffff
  }

  .coupon-filter {
    background-color: #ffffff;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 16 20;
    @include border-bottom(1, solid, #ddd);
    &-title {
      font-size: 28;
      color: $color;
    }
  }

</style>
<script>
import {WxcLoading} from 'weex-ui'
let api = require('./include/api')
let Deferred = require('Deferred')
let urlPath = require('./include/url-path')
let navigator = require('./include/xnavigator')
let queryparser = require('./include/queryparser')
let grouping = require('./include/grouping')
// let modal = weex.requireModule('modal')
let config = require('./include/app-config')
const DEFAULT_ITEM_SEARCH_PARAM = {
  page: 1,
  sort: 'NONE',
  keywords: '',
  ecomPlat: '',
  startPrice: '',
  endPrice: '',
  channelIds: '',
  catIds: '',
  taobaoMaterialId: '',
  recommend: '',
  freeShipment: false,
  searchFrom: '',
  coupon: '',
  minSales: ''
}
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-loading-more'),
    require('./mixin/page-loading'),
    require('./mixin/page-scrolltop'),
    require('./mixin/user-item-selection')
  ],
  components: {
    'shopcat-scrollbar': require('./components/shopcat-scrollbar.vue'),
    'material-scrollbar': require('./components/taobao-material-scrollbar.vue'),
    'page-notice': require('./components/page-notice.vue'),
    'searchbar': require('./components/searchbar.vue'),
    'filterbar': require('./components/filterbar.vue'),
    'navbar': require('./components/navbar.vue'),
    WxcLoading,
    'item-cell': require('./components/commission-item-cell.vue'),
    'xswitch': require('./components/switch.vue'),
    'adv-slider': require('./components/adv-slider.vue')
  },
  props: {
    height: {default: 0},
    back: {default: true},
    recommend: {default: ''},
    title: {default: null},
    searchbarShow: {default: true},
    leftTitle: {default: null}
  },
  data () {
    return {
      commissionItemList: [],
      commissionItemRowList: [],
      advSpaceId: 0,
      refreshing: false,
      refreshIndicatorScale: 0.2,
      taobaoMaterialCatId: '',
      hasNext: true,
      shopcatId: '',
      sorryIcon: 'images/aiya.png',
      topbarHide: false,
      logo: 'images/logo.png',
      itemSearchParam: Object.assign({}, DEFAULT_ITEM_SEARCH_PARAM),
      showShopcatBar: true,
      backHidden: !this.back,
      containerStyle: {},
      loadingShow: false,
      isPlus: false,
      rightItemText: '',
      navbarLeftShow: false,
      navbarLeftHidden: true,
      navbarRightShow: false,
      navbarRightHidden: true,
      selMode: false,
      showSelBtn: false,
      iosShow: false,
      loaded: false,
      searchFrom: '',
      searchFromTitle: '',
      commissionItemListLayout: 'list',
      hideEcomPlat: false
    }
  },
  created () {
    this.backHidden = !this.back
    config.bindConfig(this)
    DEFAULT_ITEM_SEARCH_PARAM.recommend = this.recommend
    if (this.height) {
      this.containerStyle.height = this.height
    }
    let params = queryparser(weex.config.bundleUrl)
    if (params.keywords) {
      params.keywords = decodeURIComponent(params.keywords)
    }
    if (params.ecomPlat) {
      this.hideEcomPlat = true
    }
    // 默认搜索本站点
    DEFAULT_ITEM_SEARCH_PARAM.searchFrom = params.searchFrom || ''
    this.searchFrom = DEFAULT_ITEM_SEARCH_PARAM.searchFrom
    if (params.title) {
      this.title = decodeURIComponent(params.title)
      delete params.title
    }
    if (params.leftTitle) {
      this.leftTitle = decodeURIComponent(params.leftTitle)
      delete params.leftTitle
    }
    if (params.advSpaceId) {
      this.advSpaceId = params.advSpaceId
    }
    Object.assign(DEFAULT_ITEM_SEARCH_PARAM, params)
    this.itemSearchParam = Object.assign({}, DEFAULT_ITEM_SEARCH_PARAM)
    if (params.channelIds) {
      this.showShopcatBar = false
    }
    if (params.backHidden && params.backHidden === 'true') {
      this.backHidden = true
    }

    if (params.showShopcat && params.showShopcat === 'true') {
      this.showShopcatBar = true
    }

    if (params.taobaoMaterialCatId) {
      this.taobaoMaterialCatId = params.taobaoMaterialCatId
    }

    this.sorryIcon = urlPath.assets(this.sorryIcon)
    this.logo = urlPath.assets(this.logo)
    Deferred.when(this.loadData(), this.searchItem()).always(() => {
      this.loaded = true
    })
    this.itemSelectionCart.change(() => {
      this.commissionItemList.forEach(item => {
        item._selected = this.checkItemSelected(item)
      })
    })
  },
  methods: {
    loadData () {
      return this.initUserItemSelection().then(() => {
        return api.page.commissionItemSearch.data({
          searchFrom: this.searchFrom
        }).done(rs => {
          setTimeout(() => {
            let data = rs.data
            // this.searchFromTitle = data.searchFromTitle
            this.isPlus = data.isPlus
            if (this.isPlus) {
              this.showSelBtn = true
            }
            this.handleNavbar()
          }, 200)
        })
      })
    },
    handleNavbar () {
      this.navbarLeftHidden = this.backHidden
      if (!this.backHidden) {
        this.navbarLeftShow = true
      }
      if (this.showSelBtn && this.iosShow) {
        this.navbarRightShow = true
      }
    },
    couponSwitchChange (val) {
      this.itemSearchParam.coupon = val ? true : ''
      this.loadingShow = true
      this.searchItem().always(() => {
        this.loadingShow = false
      })
    },
    resetSearchParam () {
      Object.assign(this.itemSearchParam, DEFAULT_ITEM_SEARCH_PARAM)
      this.hasNext = true
    },
    searchItem (append, callback) {
      // modal.alert({message: JSON.stringify(this.itemSearchParam)})
      return api.search.commissionItem(this.itemSearchParam).done((rs) => {
        rs.data.results.forEach(item => {
          item._selected = this.checkItemSelected(item)
        })
        if (append) {
          this.commissionItemList = this.commissionItemList.concat(rs.data.results)
        } else {
          this.commissionItemList = rs.data.results
        }
        this.commissionItemRowList = grouping(this.commissionItemList, 2)
        let paging = rs.data
        this.hasNext = paging.hasNext
      }).always(() => {
        callback && callback()
      })
    },
    searchBarSearch (kw) {
      DEFAULT_ITEM_SEARCH_PARAM.keywords = kw
      this.resetSearchParam()
      this.loadingShow = true
      this.itemSearchParam.keywords = kw
      this.searchItem().always(() => {
        this.loadingShow = false
      })
    },
    listLayout (layout) {
      this.commissionItemListLayout = layout
    },
    onXRefresh (event) {
      this.itemSearchParam.page = 1
      this.onRefresh(event, Deferred.when(this.loadData(), this.searchItem().always(() => {
      })))
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.itemSearchParam.page = this.itemSearchParam.page + 1
      this.searchItem(true, () => {
        this.loadingMore = false
      })
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.top)
    },
    shopcatSelected (shopcat) {
      this.loadingShow = true
      this.itemSearchParam.catIds = shopcat.id
      this.searchItem(false, rs => {

      }).always(() => {
        this.loadingShow = false
      })
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    filterbarChange () {
      this.loadingShow = true
      this.searchItem(false, rs => {
        this.loadingShow = false
      })
    },
    commissionItemClick (item) {
      if (item.id) {
        navigator.push('commission-item.js?id=' + item.id)
      } else {
        navigator.push('commission-item.js?sourceItemId=' + item.sourceItemId + '&ecomPlat=' + item.ecomPlat)
      }
    },
    navbarRightClick () {
      this.selMode = !this.selMode
    },
    searchbarClick () {
      if (!this.searchFrom) {
        navigator.push('search.js')
      }
    },
    commissionItemSel (item, flag) {
      if (!this.selectItemToSelection(item, flag)) {
        item._selected = false
      }
    },
    materialSelected (material) {
      DEFAULT_ITEM_SEARCH_PARAM.taobaoMaterialId = material.materialId
      this.loadingShow = true
      this.itemSearchParam.taobaoMaterialId = material.materialId
      this.searchItem(false, rs => {
      }).always(() => {
        this.loadingShow = false
      })
    }
  }
}
</script>
